<template>
  <t-dialog
    v-model:visible="show"
    :width="1000"
    :header="plugin.t('search')"
    destroyOnClose
    :footer="false"
    :closeOnOverlayClick="false"
  >
    <template #body>
      <t-input v-model="keyword" @change="onSearch" autofocus clearable>
        <template #prefixIcon>
          <t-icon name="search" />
        </template>
      </t-input>
      <t-table
        row-key="id"
        table-layout="auto"
        :data="list"
        :columns="columns"
        :loading="loading"
        style="margin-top: 10px"
        @rowClick="onPost"
        hover
      >
        <template #code="{ row }">
          <b>{{ row.code }}</b>
        </template>
        <template #classify="{ row }">
          <t-tag theme="primary" variant="light" v-if="row.classify">{{ row.classify.name }}</t-tag>
        </template>
        <template #name="{ row }">
          {{ row.name }}
        </template>
        <template #city="{ row }">
          {{ row.city }} {{ row.area }}
        </template>
      </t-table>
    </template>
  </t-dialog>
</template>
<script setup>
  import { ref } from 'vue'
  import app from '@/app'
  import { get } from '@/api/erp/client'
  import index from '../index'

  const emit = defineEmits(['post'])
  const plugin = index.plugin
  
  const show = ref(false)
  const list = ref([])
  const keyword = ref('')
  const loading = ref(false)
  const columns = [{
    title: plugin.t('form.code'),
    colKey: 'code',
    cell: 'code',
    fixed: 'left',
  }, {
    title: plugin.t('form.classify'),
    colKey: 'classify',
    cell: 'classify'
  }, {
    title: plugin.t('form.name'),
    colKey: 'name',
    cell: 'name'
  }, {
    title: plugin.t('form.phone'),
    colKey: 'phone'
  }, {
    title: plugin.t('form.email'),
    colKey: 'email'
  }, {
    title: plugin.t('form.city') + '/' + plugin.t('form.area'),
    colKey: 'city',
    cell: 'city'
  }]

  const open = () => {
    show.value = true
  }

  // 加载
  const getData = async () => {
    list.value = []
    await searchClient('name')
    await searchClient('code')
    await searchClient('phone')
    await searchClient('email')
    loading.value = false
  }

  // 查询
  const searchClient = type => {
    return new Promise((resolve, reject) => {
      // 存在数据将不查询
      if(list.value.length) {
        return resolve()
      }
      get({ [type]: keyword.value }).then(res => {
        list.value = res.data
        resolve()
      })
    })
  }

  // 定时查询
  let timer = {}
  const onSearch = async () => {
    loading.value = true
    clearTimeout(timer)
    timer = setTimeout(() => getData(), 500)
  }

  // 确认
  const onPost = ({ row }) => {
    emit('post', row)
    show.value = false
  }

  getData()

  defineExpose({ open })
</script>